import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useState, useEffect, useRef } from "react";
import { formatChildTree, isChildDataType } from "../RowMerge/tools";
import { getDsToZlData } from "../../api/DesignTableApi";
import Draggable from "react-draggable";
//import {filterCpasTable } from './tools';
import { FilterOutlined, ExclamationCircleOutlined,
// CheckOutlined,
 } from "@ant-design/icons";
import { Checkbox, Card, Select, Modal, message, TreeSelect, Col, Row, InputNumber, Form, } from "antd";
import { Button } from "devextreme-react/button";
import "./_style.less";
const CheckboxGroup = Checkbox.Group;
//判断列数据是否重复
function isRepeatColumn(arr, val) {
    let isRepeat = false;
    if (!arr || !arr.length || !val) {
        return isRepeat;
    }
    for (let i = 0; i < arr.length; i++) {
        const { value, children } = arr[i];
        if (val === value) {
            isRepeat = true;
        }
        else {
            if (children && children.length) {
                isRepeat = isRepeatColumn(children, val);
            }
        }
    }
    return isRepeat;
}
const FilterModalComponent = (props) => {
    const { isOpen, handleOpen, _this } = props;
    const [filterForm] = Form.useForm();
    const { setFieldsValue } = filterForm;
    const [selectColumnNum, setSelectColumnNum] = useState(null);
    const [columnData, setColumnData] = useState([]);
    const [disabled, setDisabled] = useState(true);
    const [bounds, setBounds] = useState({
        left: 0,
        top: 0,
        bottom: 0,
        right: 0,
    });
    const draggleRef = useRef(null);
    const plainOptions = [
        {
            label: "前",
            value: "front",
        },
        {
            label: "后",
            value: "after",
        },
    ];
    //获取列数据
    const getColumnData = () => {
        const { header } = _this.gridRef.dsSourceData;
        const headerData = header.slice(1, header.length - 1);
        let selcetOptions = [];
        for (let i = 0; i < headerData.length; i++) {
            const currentHead = headerData[i];
            let prevHeadChildLen = 0;
            if (i > 0) {
                const prevHead = headerData[i - 1];
                if (prevHead?.children && prevHead?.children.length) {
                    prevHeadChildLen =
                        prevHead?.children && prevHead?.children.length
                            ? prevHead?.children.length - 1
                            : 0;
                }
            }
            const columnNum = i + 1 + prevHeadChildLen;
            headerData[i].columnNum = columnNum;
            const headChild = currentHead.children;
            if ((currentHead.type === "numeric" ||
                currentHead.config.type === "numeric") &&
                !headChild) {
                selcetOptions.push({
                    key: headerData[i].columnNum,
                    label: currentHead.label,
                    columnNum: headerData[i].columnNum,
                    value: `${currentHead.label}${headerData[i].columnNum}${i}`,
                });
            }
            if (headChild && headChild.length) {
                const isChildData = isChildDataType(headChild, "numeric");
                if (isChildData) {
                    const children = formatChildTree(currentHead.children, columnNum, "numeric");
                    selcetOptions.push({
                        key: headerData[i].columnNum,
                        label: currentHead.label,
                        columnNum: headerData[i].columnNum,
                        value: `${currentHead.label}${headerData[i].columnNum}${i}`,
                        children,
                    });
                }
            }
        }
        setColumnData([...selcetOptions]);
        return selcetOptions;
    };
    const loadFilterFetchApi = async () => {
        const columnData = await getColumnData();
        const { tableConfig = {} } = _this.gridRef.getCpasTableGrid();
        let { filterCfg = {} } = tableConfig;
        console.log(filterCfg, "filterCfg1111");
        const currentColumnNum = filterCfg?.columnNum
            ? filterCfg?.columnNum
            : selectColumnNum;
        if (currentColumnNum && columnData && columnData.length) {
            setSelectColumnNum(currentColumnNum);
        }
        else if (!currentColumnNum && columnData && columnData.length) {
            const currentData = columnData[0];
            setSelectColumnNum(currentData.columnNum);
        }
        /*if (!selectColumnNum && columnData && columnData.length) {
          setSelectColumnNum(columnData[0].columnNum);
        }*/
        if (filterCfg && Object.keys(filterCfg).length > 0) {
            if (columnData && columnData.length) {
                if (filterCfg?.column_val) {
                    const isResult = isRepeatColumn(columnData, filterCfg.column_val);
                    if (!isResult && filterCfg.column_val) {
                        filterCfg.column_val = columnData[0].value;
                    }
                }
            }
            setFieldsValue(filterCfg);
            setSelectColumnNum(filterCfg.selectColumnNum);
        }
        else {
            setFieldsValue({
                num: "",
                order: "front",
                column_val: columnData && columnData.length ? columnData[0].value : "",
                is_blank_row: false,
                is_blank_data_row: false,
                selectColumnNum: columnData && columnData.length ? columnData[0].columnNum : "",
            });
            //setSelectColumnNum(filterCfg.selectColumnNum);
        }
    };
    useEffect(() => {
        loadFilterFetchApi();
    }, [isOpen]);
    const onSelectChange = (value, label, extra) => {
        const columnNum = extra.triggerNode.props.columnNum
            ? extra.triggerNode.props.columnNum
            : 0;
        setSelectColumnNum(columnNum);
    };
    const onClearTable = async () => {
        console.log("clear table");
        setFieldsValue({
            num: "",
            order: "front",
            column_val: columnData && columnData.length ? columnData[0].value : "",
            is_blank_row: false,
            is_blank_data_row: false,
            selectColumnNum: columnData && columnData.length ? columnData[0].columnNum : "",
        });
        delete _this.gridRef.tableConfig["filterCfg"];
        const dsSourceData = _this.gridRef.dsSourceData;
        const dsFormulaSourceData = _this.gridRef.props.dsTableRef.getFormulaSourceData();
        const tableConfig = _this.gridRef.tableConfig;
        console.log(tableConfig, "tableConfig111111this", _this);
        try {
            const tid = _this?.gridRef?.props?.notes?.tid;
            const zlTableData = await getDsToZlData(dsSourceData, {
                ...tableConfig,
            }, dsFormulaSourceData, tid);
            if (zlTableData && zlTableData.data) {
                const zlTransformData = zlTableData.data;
                //zlGridData 除了拆表的转数逻辑 , 数据库会存储该数据
                //zlDivideData 拆表后的转数逻辑
                //zlGridData 存储在隐藏的CpasTable中，为了ref正确使用, 真正渲染调用afterDivideTableRender用数组。
                const { zlGridData, zlDivideData } = zlTransformData;
                await _this.gridRef.reloadTable(zlGridData, "zl", dsSourceData);
                const refs = await _this.gridRef.afterDivideTableRender(zlDivideData);
                //更新整理模式下cpastable实例
                _this.gridRef && _this.gridRef?.dsTableRef?.setZlCpasTableRefs(refs);
                handleOpen(false);
                message.success("筛选条件清空成功");
                _this.gridRef.setTableContentChange(true, {
                    type: "筛选清空",
                    params: {},
                });
            }
        }
        catch (e) {
            message.error("操作失败，请检查配置项重试");
            throw e;
        }
    };
    const onCancel = () => {
        console.log("onCancel");
        if (columnData && columnData.length) {
            setSelectColumnNum(columnData[0].columnNum);
        }
        else {
            setSelectColumnNum(null);
        }
        handleOpen(false);
    };
    const onFinishSave = async () => {
        let formValues = filterForm.getFieldsValue(); // 获取表单数据
        const { num, is_blank_row, is_blank_data_row } = formValues;
        formValues["selectColumnNum"] = selectColumnNum;
        console.log("表单数据:", formValues);
        console.log(selectColumnNum, "selectColumnNum");
        const dsSourceData = _this.gridRef.dsSourceData;
        console.log(_this, "_this111");
        const dsFormulaSourceData = _this.gridRef.props.dsTableRef.getFormulaSourceData();
        const { tableConfig } = _this.gridRef.getCpasTableGrid();
        console.log(dsFormulaSourceData, "dsFormulaSourceData1");
        let newTableCfg = {
            ...tableConfig,
            filterCfg: {
                ...formValues,
            },
        };
        // if (num || is_blank_row || is_blank_data_row) {
        //   newTableCfg = {
        //     ...tableConfig,
        //     filterCfg: {
        //       ...formValues,
        //     },
        //   };
        // }
        console.log(newTableCfg, "newTableCfg");
        try {
            /**本地调试专用 */
            /*let zlTableData: any = {};
            const data = filterCpasTable(
              dsSourceData,
              newTableCfg,
            );
            zlTableData.data = data;*/
            const tid = _this?.gridRef?.props?.notes?.tid;
            const zlTableData = await getDsToZlData(dsSourceData, newTableCfg, dsFormulaSourceData, tid);
            if (zlTableData && zlTableData.data) {
                const zlTransformData = zlTableData.data;
                //zlGridData 除了拆表的转数逻辑 , 数据库会存储该数据
                //zlDivideData 拆表后的转数逻辑
                //zlGridData 存储在隐藏的CpasTable中，为了ref正确使用, 真正渲染调用afterDivideTableRender用数组。
                const { zlGridData, zlDivideData } = zlTransformData;
                await _this.gridRef.reloadTable(zlGridData, "zl", dsSourceData);
                const refs = await _this.gridRef.afterDivideTableRender(zlDivideData);
                //更新整理模式下cpastable实例
                _this.gridRef && _this.gridRef?.dsTableRef?.setZlCpasTableRefs(refs);
                handleOpen(false);
                message.success("筛选条件设置成功");
                _this.gridRef.setTableContentChange(true, {
                    type: "筛选保存",
                    params: {
                        ...newTableCfg.filterCfg,
                    },
                });
            }
        }
        catch (e) {
            message.error("操作失败，请检查配置项重试");
            throw e;
        }
    };
    const tableSettingLeft = () => {
        return (_jsxs(React.Fragment, { children: [_jsx(FilterOutlined, { style: { color: "green" } }), " \u7B5B\u9009"] }));
    };
    const tableSettingRight = () => {
        return (_jsxs(React.Fragment, { children: [_jsx(Button, { onClick: () => onClearTable(), type: "default", children: "\u7B5B\u9009\u6E05\u7A7A" }), _jsx(Button, { onClick: onFinishSave, type: "default", children: "\u786E\u5B9A" })] }));
    };
    const onStart = (_event, uiData) => {
        const { clientWidth, clientHeight } = window.document.documentElement;
        const targetRect = draggleRef.current?.getBoundingClientRect();
        if (!targetRect) {
            return;
        }
        setBounds({
            left: -targetRect.left + uiData.x,
            right: clientWidth - (targetRect.right - uiData.x),
            top: -targetRect.top + uiData.y,
            bottom: clientHeight - (targetRect.bottom - uiData.y),
        });
    };
    return (_jsx(React.Fragment, { children: _jsx(Modal, { open: isOpen, width: "90%", onCancel: onCancel, footer: null, className: "setting zl-modal", keyboard: false, maskClosable: false, destroyOnClose: true, forceRender: true, title: _jsx(Card, { title: tableSettingLeft(), extra: tableSettingRight(), bordered: false, className: "merge-card-title", style: {
                    cursor: "move",
                }, onMouseOver: () => {
                    if (disabled) {
                        setDisabled(false);
                    }
                }, onMouseOut: () => {
                    setDisabled(true);
                }, 
                // fix eslintjsx-a11y/mouse-events-have-key-events
                // https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/mouse-events-have-key-events.md
                onFocus: () => { }, onBlur: () => { } }), modalRender: (modal) => (_jsx(Draggable, { disabled: disabled, bounds: bounds, nodeRef: draggleRef, onStart: (event, uiData) => onStart(event, uiData), children: _jsx("div", { ref: draggleRef, children: modal }) })), children: _jsx("div", { className: "filter-card-content", children: _jsx("div", { className: "filter-condition", children: _jsxs(Form, { form: filterForm, name: "filter_form", layout: "inline", onFinish: onFinishSave, initialValues: {
                            column_val: columnData && columnData.length ? columnData[0].value : "",
                            order: plainOptions[0].value,
                        }, children: [_jsxs(Row, { children: [_jsxs(Col, { span: 14, children: [_jsx(Form.Item, { name: "column_val", label: "\u8BF7\u9009\u62E9\u5217\uFF1A", children: _jsx(TreeSelect, { onChange: onSelectChange, dropdownMatchSelectWidth: false, treeData: columnData, treeDefaultExpandAll: true, style: { width: 150 } }) }), _jsx(Form.Item, { name: "order", children: _jsx(Select, { options: plainOptions }) }), _jsx(Form.Item, { name: "num", children: _jsx(InputNumber, { min: 1 }) }), "\u540D"] }), _jsx(Col, { span: 4, className: "filter-hidden-row", children: _jsx(Form.Item, { name: "is_blank_row", valuePropName: "checked", children: _jsx(Checkbox, { children: "\u9690\u85CF\u7A7A\u884C" }) }) }), _jsx(Col, { span: 4, className: "filter-hidden-row", children: _jsx(Form.Item, { name: "is_blank_data_row", valuePropName: "checked", children: _jsx(Checkbox, { children: "\u9690\u85CF\u7A7A\u6570\u636E\u884C" }) }) })] }), _jsxs(Row, { className: "filter-tips", children: [_jsx(ExclamationCircleOutlined, { style: { color: "#FF7D1E" } }), "\u00A0\u63D0\u793A\uFF1A\u7B5B\u9009\u540E\uFF0C\u5C06\u65E0\u6CD5\u6267\u884C\u5F52\u5E76\uFF0C\u8BF7\u5148\u6267\u884C\u5F52\u5E76\u6216\u6E05\u7A7A\u7B5B\u9009\u6761\u4EF6\u518D\u5F52\u5E76\uFF01"] })] }) }) }) }) }));
};
export default FilterModalComponent;
